using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Win32;
using OfficeOpenXml;
using System.IO;
using ErpManager.WPF.Models;
using ErpManager.WPF.Services;

namespace ErpManager.WPF.ViewModels
{
    public class OutboundViewModel : INotifyPropertyChanged
    {
        private readonly ApplicationDbContext _context;
        private readonly LogService _logService;
        private DateTime _startDate = DateTime.Today.AddDays(-30);
        private DateTime _endDate = DateTime.Today;
        private Dealer? _selectedDealer;
        private Product? _selectedProduct;
        private int _quantity;
        private string _errorMessage = string.Empty;
        private bool _isLoading;

        public ObservableCollection<OutboundRecord> OutboundRecords { get; } = new();
        public ObservableCollection<Dealer> Dealers { get; } = new();
        public ObservableCollection<Product> Products { get; } = new();

        public event PropertyChangedEventHandler? PropertyChanged;

        public DateTime StartDate
        {
            get => _startDate;
            set
            {
                _startDate = value;
                OnPropertyChanged(nameof(StartDate));
                _ = LoadOutboundRecords();
            }
        }

        public DateTime EndDate
        {
            get => _endDate;
            set
            {
                _endDate = value;
                OnPropertyChanged(nameof(EndDate));
                _ = LoadOutboundRecords();
            }
        }

        public Dealer? SelectedDealer
        {
            get => _selectedDealer;
            set
            {
                _selectedDealer = value;
                OnPropertyChanged(nameof(SelectedDealer));
                _ = LoadOutboundRecords();
            }
        }

        public Product? SelectedProduct
        {
            get => _selectedProduct;
            set
            {
                _selectedProduct = value;
                OnPropertyChanged(nameof(SelectedProduct));
            }
        }

        public int Quantity
        {
            get => _quantity;
            set
            {
                _quantity = value;
                OnPropertyChanged(nameof(Quantity));
            }
        }

        public string ErrorMessage
        {
            get => _errorMessage;
            set
            {
                _errorMessage = value;
                OnPropertyChanged(nameof(ErrorMessage));
            }
        }

        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged(nameof(IsLoading));
            }
        }

        public ICommand AddOutboundCommand { get; }
        public ICommand ExportToExcelCommand { get; }
        public ICommand RefreshCommand { get; }

        public OutboundViewModel(ApplicationDbContext context)
        {
            _context = context;
            _logService = new LogService(context, "system", "系统");
            AddOutboundCommand = new RelayCommand(async () => await AddOutbound(), CanAddOutbound);
            ExportToExcelCommand = new RelayCommand(async () => await ExportToExcel());
            RefreshCommand = new RelayCommand(async () => await LoadOutboundRecords());

            // 初始加载数据
            _ = LoadDealers();
            _ = LoadProducts();
            _ = LoadOutboundRecords();
        }

        private async Task LoadDealers()
        {
            try
            {
                var dealers = await _context.Dealers.OrderBy(d => d.DealerName).ToListAsync();
                Dealers.Clear();
                foreach (var dealer in dealers)
                {
                    Dealers.Add(dealer);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = $"加载经销商列表失败: {ex.Message}";
            }
        }

        private async Task LoadProducts()
        {
            try
            {
                var products = await _context.Products.OrderBy(p => p.ProductName).ToListAsync();
                Products.Clear();
                foreach (var product in products)
                {
                    Products.Add(product);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = $"加载产品列表失败: {ex.Message}";
            }
        }

        private async Task LoadOutboundRecords()
        {
            try
            {
                IsLoading = true;
                ErrorMessage = string.Empty;

                var query = _context.OutboundRecords
                    .Include(r => r.Dealer)
                    .Include(r => r.Product)
                    .Where(r => r.OutboundDate >= StartDate && r.OutboundDate <= EndDate.AddDays(1));

                if (SelectedDealer != null)
                {
                    query = query.Where(r => r.DealerId == SelectedDealer.DealerId);
                }

                var records = await query
                    .OrderByDescending(r => r.OutboundDate)
                    .ToListAsync();

                OutboundRecords.Clear();
                foreach (var record in records)
                {
                    OutboundRecords.Add(record);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = $"加载出库记录失败: {ex.Message}";
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task AddOutbound()
        {
            try
            {
                if (!CanAddOutbound())
                {
                    return;
                }

                var record = new OutboundRecord
                {
                    DealerId = SelectedDealer!.DealerId,
                    ProductId = SelectedProduct!.ProductId,
                    Quantity = Quantity,
                    OutboundDate = DateTime.Now,
                    CreateTime = DateTime.Now
                };

                _context.OutboundRecords.Add(record);
                await _context.SaveChangesAsync();

                // 重新加载记录以获取包含导航属性的完整记录
                await _context.Entry(record).Reference(r => r.Dealer).LoadAsync();
                await _context.Entry(record).Reference(r => r.Product).LoadAsync();

                // 记录添加出库记录日志
                await _logService.LogOperationAsync("出库管理", "添加", 
                    $"添加出库记录：经销商 {record.Dealer?.DealerName}，产品 {record.Product?.ProductName}，数量 {record.Quantity}");

                OutboundRecords.Insert(0, record);
                ClearForm();
                ErrorMessage = string.Empty;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"添加出库记录失败: {ex.Message}";
            }
        }

        private async Task ExportToExcel()
        {
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "Excel files (*.xlsx)|*.xlsx",
                Title = "选择导出位置",
                FileName = $"出库记录_{DateTime.Now:yyyyMMdd}.xlsx"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using var package = new ExcelPackage();
                    var worksheet = package.Workbook.Worksheets.Add("出库记录");

                    // 添加标题行
                    worksheet.Cells[1, 1].Value = "经销商";
                    worksheet.Cells[1, 2].Value = "产品";
                    worksheet.Cells[1, 3].Value = "数量";
                    worksheet.Cells[1, 4].Value = "出库日期";

                    // 添加数据
                    int row = 2;
                    foreach (var record in OutboundRecords)
                    {
                        worksheet.Cells[row, 1].Value = record.Dealer?.DealerName;
                        worksheet.Cells[row, 2].Value = record.Product?.ProductName;
                        worksheet.Cells[row, 3].Value = record.Quantity;
                        worksheet.Cells[row, 4].Value = record.OutboundDate;
                        row++;
                    }

                    // 设置列宽
                    worksheet.Columns.AutoFit();

                    // 保存文件
                    await package.SaveAsAsync(new FileInfo(saveFileDialog.FileName));
                    ErrorMessage = "导出成功！";
                }
                catch (Exception ex)
                {
                    ErrorMessage = $"导出失败: {ex.Message}";
                }
            }
        }

        private bool CanAddOutbound()
        {
            return SelectedDealer != null &&
                   SelectedProduct != null &&
                   Quantity > 0;
        }

        private void ClearForm()
        {
            SelectedProduct = null;
            Quantity = 0;
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
